"""
Case Type   : 多块预读
Case Name   : 开启预读块，查询视图是否多块预读基表
Create At   : 2024/12/05
Owner       : @li-xin12345
Description :
    1、建表，建视图，重启
    2、查询视图扫描表
    3、清理环境
Expect      :
    1、成功
    2、成功
    3、成功
History     :
"""
import os
import unittest

from yat.test import Node
from yat.test import macro

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger


class SessionTest(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.constant = Constant()
        self.common = Common()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_user_node = Node('PrimaryDbUser')
        self.tb_name = 't_multi_bulk_read_0018'
        self.view_name = 'v_multi_bulk_read_0018'
        self.pg_log = \
            os.path.join(macro.PG_LOG_PATH, macro.DN_NODE_NAME.split('/')[0])

    def test_multi_bulk_read(self):
        text = '----step1: 建表，建视图，重启；expect: 成功----'
        self.log.info(text)
        sql = f'''drop table if exists {self.tb_name} cascade;
        create table {self.tb_name} (
            o_orderkey bigint not null,
            o_custkey integer not null,
            o_orderstatus char(1) not null,
            o_totalprice decimal(15,2) not null,
            o_orderdate date not null,
            o_orderpriority char(15) not null,
            o_clerk char(15) not null,
            o_shippriority integer not null,
            o_comment varchar(79) not null
        );
        insert into {self.tb_name}
        values (generate_series(1000, 1000000, 2), 4063478, 'F', 93255.68, 
        '1994-04-20', '1-URGENT', 'Clerk#000008803', 0, 
        'haggle blithely above the accounts. blithely fina');
        create view {self.view_name} as select * from {self.tb_name};
        '''
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, res, f'执行失败：{text}')
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, res,
                      f'执行失败：{text}')
        self.assertIn('INSERT 0 499501', res, f'执行失败：{text}')
        self.assertIn(self.constant.CREATE_VIEW_SUCCESS_MSG, res,
                      f'执行失败：{text}')

        msg = self.pri_sh.restart_db_cluster()
        self.log.info(msg)
        status = self.pri_sh.get_db_cluster_status()
        self.assertTrue("Degraded" in status or "Normal" in status)

        text = '----step2: 查询视图扫描表；expect: 成功----'
        self.log.info(text)
        sql = f"set heap_bulk_read_size = 20;" \
              f"select * from {self.view_name};"
        self.log.info(sql)
        res = self.pri_sh.execut_db_sql(sql)
        self.assertIn(self.constant.SET_SUCCESS_MSG, res, f'执行失败：{text}')
        self.log.info(res.splitlines()[-1])
        self.assertEqual(res.splitlines()[-1].split()[0].split('(')[1],
                         '499501')

        self.log.info('--查看日志中打印的预读块数量--')
        cmd = f"cd {self.pg_log};" \
              f"ls -t | head -1 | awk '{{{{print $1}}}}' | " \
              f"xargs cat | tail -30 | " \
              f"grep 'End of pre-Read, the max blocks batch is'"
        self.log.info(cmd)
        res = self.common.get_sh_result(self.pri_user_node, cmd)
        self.log.info(res)
        self.assertIsNotNone(res, f'执行失败：{text}')

    def tearDown(self):
        text = '----step3: 清理环境;expect:成功----'
        self.log.info(text)
        sql = f"drop table if exists {self.tb_name} cascade;"
        res = self.pri_sh.execut_db_sql(sql)
        self.log.info(res)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS, res, f'执行失败：{text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
